// @ts-nocheck

import { Component, Vue, Prop, Emit } from 'vue-property-decorator';
import ComMap from '../map/index.vue';
import { getstyleJson, getTools } from '@/utils';
import { MAP_CONFIG } from '../map/mapconfig';
import jsonp from 'jsonp';

@Component({
  components: {
    ComMap
  }
})
export default class AppMap extends Vue {

  @Prop({
    required: false,
    default: () => {
      return {
        button: true,
        search: true,
        serviceCommunication: false,
        tools: true
      }
    },
  }) handles!: any;

  @Prop({
    required: false,
    default: () => 'dom_map',
  }) domID!: string;

  @Prop({
    required: false,
    default: () => true,
  }) initFlag!: boolean;

  @Prop({
    required: false,
    default: () => MAP_CONFIG,
  }) mapConfig!: any;

  @Prop({
    required: false,
    default: () => '',
  }) mapConfigName!: string;

  @Prop({
    required: false,
    default: () => false,
  })
  postMessageFlag!: boolean

  url: string = 'http://api.map.baidu.com/reverse_geocoding/v3/?ak=xoLQGps93RgS0jSylK15n55RbPocQMhG&output=json&coordtype=wgs84ll&location=';
  flag: boolean = true;
  styleJson: any = getstyleJson();
  selectItem: any;
  suggestions: any[] = [];
  suggestion: any;
  pointStyle: any = { styleType: 2, radius: 5, fillColor: '#ff0000', iconUrl: '/assets/images/location.png' };
  page: number = 0;
  loading: boolean = true;
  resources: any[] = [];
  selectedResources: any[] = [];
  pointResource: any;
  pointLayer: any;

  show: boolean = true;
  tools: any[] = getTools();
  anotherTool: any = {
    icon: '', type: -1, select: false
  };
  layTool: any;
  parser: any;

  nextMessage: any = {};

  @Emit('onMapLoaded')
  onMapLoaded(event: any) {
    this.$nextTick(() => {
      this.nextMessage['mapcore'] = event.mapcore;
      this.nextMessage['view'] = event.view;
      if (event.mapcore) {
        this.pointLayer = this.comMap.addVectorLayer('pointLayer');
  
        // 地图工具栏
        this.layTool = this.addVectorLayer('layTool');
        this.parser = this.addParser();
      }
      return { mapcore: event.mapcore, view: event.view };
    });
  }

  get comMap(): any {
    return this.$refs.comMap;
  }

  /** 启动定位 */
  startSelectPoint(context, callback) {
    this.comMap.setMark(context, callback);
  }

  /** 添加点 */
  addPoints(point) {
    this.comMap.addPoints(point);
  }

  /** 在指定图层添加点 **/
  addPointsByLayer(vectorLayer, points) {
    this.comMap.addPointsByLayer(vectorLayer, points);
  }

  /** 图层清理 */
  layerClear(layerId) {
    if (layerId !== '') {
      this.comMap.clearVectorLayerByLayerId(layerId);
    } else {
      this.comMap.clearDefaultVectorLayer();
    }
  }

  /** 范围 */
  fitExtent(extent) {
    this.comMap.fitExtent(extent);
  }

  fitLayerExtent(layer, map: any = null) {
    this.comMap.fitLayerExtent(layer, map);
  }

  /** 通过坐标点反向获取地址信息 */
  async getPointsFormattedAddress(params) {
    let url = `${this.url}${params}&cb=callback`;
    return new Promise((resolve, reject) => {
      jsonp(url, (err, data) => {
        if (!err) {
          resolve(data)
        } else {
          reject(err)
        }
      })
    })
  }

  /** 在默认图层上添加GeoJson对象 */
  addGeoJsonObject(features, layerClearFlag: boolean = true, styleJson: any = this.styleJson, fitFlag: boolean = true) {
    let geoJson = {
      'type': 'FeatureCollection',
      'crs': {
        'type': 'name',
        'properties': {
          'name': 'EPSG:3857'
        }
      }
    };
    geoJson['features'] = features;
    if (layerClearFlag) {
      this.layerClear('');
    }
    this.comMap.addGeoJsonObject(geoJson, styleJson);
    fitFlag && this.fitLayerExtent(null);
  }

  /** 开始绘制几何图形 */
  startDraw(geoType, drawEndCallback, self) {
    this.layerClear('');
    this.comMap.startDraw(geoType, drawEndCallback, self);
  }

  /** 结束绘制几何图形 */
  endDraw() {
    this.comMap.endDraw();
  }

  /** 添加图层 **/
  addVectorLayer(layerId: string, map: any = null): any {
    let layer = this.comMap.addVectorLayer(layerId, map);
    this.comMap[layerId] = layer;
    return layer;
  }

  /** 添加图形 **/
  addGeoJsonObjectByLayer(vectorLayer: any, features: any, styleJson: any = this.styleJson, map: any = null, flag: boolean = true) {
    let geoJson = {
      'type': 'FeatureCollection',
      'crs': {
        'type': 'name',
        'properties': {
          'name': 'EPSG:3857'
        }
      }
    };
    geoJson['features'] = features;
    this.comMap.addGeoJsonObjectByLayer(vectorLayer, geoJson, styleJson);
    if (flag) {
      this.comMap.fitLayerExtent(vectorLayer, map);
    }
  }

  /** 获取网格空间数据 */
  getGrids(event: number) {
    this.selectItem = event;
    if (event < 0) {
      this.mdlSnackbarService.showToast('该行政数据暂时未开通！');
      return;
    }
    this.layerClear('');
    this.mapLocationService.getGeomByRegionLevel('411522', event).subscribe((data: any[]) => {
      if (!data) {
        return;
      }
      let features: any[] = [];
      data.forEach((d, i) => {
        let feature = { 'type': 'Feature', 'geometry': JSON.parse(d.geom), 'name': d.regionName };
        features.push(feature);
        if (i === data.length - 1) {
          this.addGeoJsonObject(features);
        }
      });
    });
  }

  /** 鼠标点击事件 **/
  addMapClickEvent(context: any, callback: any, map: any = null) {
    this.comMap.addMapClickEvent(context, callback, map);
  }

  /** 轨迹 **/
  drawTrack(vectorLayer: any, trackList: any) {
    if (!vectorLayer) {
      vectorLayer = this.comMap['defaultVectorLayer'];
    }
    this.comMap.drawTrack(vectorLayer, trackList);
  }

  addOverlay(element: any, autoPan: any) {
    return this.comMap.addOverlay(element, autoPan);
  }

  clearOverlays() {
    this.comMap.clearOverlays();
  }

  search(event: { query: any; }) {
    this.mapLocationService.searchLocation(event.query, 0).subscribe((data: any[]) => {
      this.suggestions = data;
    });
  }

  selectSuggestion() {
    let point = {
      geometry: { x: this.suggestion.lng, y: this.suggestion.lat },
      style: this.pointStyle,
      attr: { 'data': this.suggestion }
    };
    this.addPoints([point]);
    this.fitLayerExtent(null);
    if (this.handles['serviceCommunication']) {
      // type: 1.搜索坐标点
      // this.mapLocationService.announceMission({type: 1, event: {coordinate: [this.suggestion.lng, this.suggestion.lat]}});
    }
  }

  /** 鼠标悬浮事件 */
  pointerMove(context: any, callback: any, map: any = null) {
    this.comMap.pointerMove(context, callback, map);
  }

  /** 移动缩放事件 */
  moveendMap(context: any, callback: any) {
    this.comMap.moveendMap(context, callback);
  }

  viewChange(params: any) {
    this.comMap.viewChange(params);
  }

  layerSelect(event: any) {
    let points: any[] = [];
    this.selectedResources.forEach(r => {
      if (r.data.type === 'P') {
        this.pointResource[r['id']].forEach(p => {
          p['style'] = { styleType: 2, radius: 5, fillColor: 'rgba(0,0,0,0)', iconUrl: r.type, attr: '' };
          points.push(p);
        });
      }
    });
    this.pointLayer.getSource().clear();
    this.comMap.addPointsByLayer(this.pointLayer, points);
    this.comMap.fitLayerExtent(this.pointLayer);
  }

  setCenter(point: any) {
    this.comMap.setCenter(point);
  }

  updateMapSize() {
    this.comMap.updateMapSize();
  }

  addGridCharts(extent: any, colNum: any, rowNum: any, data: any, valueColors: any, max = 3000) {
    return this.comMap.addGridCharts(extent, colNum, rowNum, data, valueColors, max);
  }

  addMapScatterCharts(geoCoordMap, data, max = 3000) {
    return this.comMap.addMapScatterCharts(geoCoordMap, data, max);
  }

  addHeatMapLayer(layerID, map: any = null) {
    return this.comMap.addHeatMapLayer(layerID, map);
  }

  addHeatMapPoints(heatMapLayer, points) {
    this.comMap.addHeatMapPoints(heatMapLayer, points);
  }

  /**
   * 缓冲区声明
   */
  addParser() {
    return this.comMap.addParser();
  }

  /**
   * 获取地图中心点
   */
  getCenter() {
    return this.comMap.getCenter();
  }

  /**
   * 获取地图实例
   */
  getMap() {
    return this.comMap.getMap();
  }

  /**
   * 获取地图初始阿视图
   */
  getInitView() {
    // return this.comMap.getInitView();
    this.comMap.getInitView();
  }

  /**
   * 创建地图
   * @param domId
   * @param view
   */
  creatMap(domId, view) {
    return this.comMap.creatMap(domId, view);
  }

  addFeatures(layer, event) {
    this.comMap.addFeatures(layer, event);
  }

  /** 通过坐标点反向获取地址信息 */
  getInterestPoi(coordinatex, coordinatey) {
    return this.http.get('/system/api/grid/getInterestPoi?coordinatex=' + coordinatex + '&coordinatey=' + coordinatey).pipe(
      map((res: Response) => res['data'])
    );
  }

  // 工具栏切换
  change(tool, index) {
    switch (tool.type) {
      case -1:
        this.show = false;
        this.tools.forEach(v => { v.select = false; });
        break;
      case 0:
        let view = this.getMap().getView();
        // 获取地图当前缩放等级
        let zoom = view.getZoom();
        // 每单击一次地图的缩放等级减一，以实现地图缩小
        view.setZoom(zoom - 1);
        break;
      case 1:
        let views = this.getMap().getView();
        let zooms = views.getZoom();
        views.setZoom(zooms + 1);
        break;
      case 2:
        this.comMap.fullScreen();
        break;
      case 3:
        this.initTools(tool, index);
        this.layTool.getSource().clear();
        this.clearOverlays();
        if (this.tools[index].select) {
          this.comMap.clearDefaultVectorLayer();
          this.comMap.endMark();
          this.comMap.startDrawAndCallback('LineString', this.drawStartCallback, this, this.drawEndCallback);
        } else {
          this.endDraw();
          this.onLocationMapLoaded.next(this.nextMessage);
        }
        break;
      case 4:
        this.initTools(tool, index);
        this.layTool.getSource().clear();
        this.clearOverlays();
        if (this.tools[index].select) {
          this.comMap.clearDefaultVectorLayer();
          this.comMap.endMark();
          this.comMap.startDrawAndCallback('Polygon', this.drawStartCallback, this, this.drawEndCallback);
        } else {
          this.endDraw();
          this.onLocationMapLoaded.next(this.nextMessage);
        }
        break;
      case 6:
        this.show = true;
        this.layTool.getSource().clear();
        this.clearOverlays();
        this.endDraw();
        break;
    }
  }

  initTools(tool, index) {
    this.tools.forEach((v, i) => {
      if (v.select) {
        this.endDraw();
      }
      if (index === i) {
        v.select = !tool.select;
      } else {
        v.select = false;
      }
    });
  }

  drawStartCallback(output, self) {
    // console.log(output);
  }

  drawEndCallback(geometry, self) {
    let jstGeom = self.parser.read(geometry);
    let bufferedGeometry = self.parser.write(jstGeom);
    self.addFeatures(self.layTool, bufferedGeometry);
  }

  postMessage(params) {
    if (postMessageFlag) {
      this.$event.$emit('mapPostMessage', params)
    }
  }

}